package com.travel.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.travel.dto.OderDTO;
import com.travel.dto.UserInfoDTO;
import com.travel.enums.OrderStates;
import com.travel.pojo.User;
import com.travel.pojo.UserOrder;
import com.travel.result.Result;
import com.travel.service.UserOrderService;
import com.travel.service.UserService;
import com.travel.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @program: travel
 * @author: lvyaxin
 * @create: 2024-07-08 09:23
 **/
@RestController
@RequestMapping("/api/tourist")
@Api(tags = "游客管理接口")
@Slf4j
public class TouristController {

    @Autowired
    private UserOrderService userOrderService;

    @Autowired
    private UserService userService;

    // 07-07 根据游客id查询全部订单
    @GetMapping("/list/{id}")
    @ApiOperation("根据游客id查询全部订单")
    public Result<List<UserOrder>> listById(@PathVariable String id){
        LambdaQueryWrapper<UserOrder> wrapper = new LambdaQueryWrapper<UserOrder>()
                .eq(UserOrder::getUserId, id)
                .eq(UserOrder::getDeleteStatus, 0)
                .orderByDesc(UserOrder::getAddTime);
        List<UserOrder> list = userOrderService.list(wrapper);
        return Result.ok(list);
    }

    // 07-07 根据游客id和状态查询订单
    @GetMapping("/list/{id}/{state}")
    @ApiOperation("根据游客id和订单状态查询订单")
    public List<UserOrder> listByState(@PathVariable String id, @PathVariable String state){
        LambdaQueryWrapper<UserOrder> wrapper = new LambdaQueryWrapper<UserOrder>()
                .eq(UserOrder::getUserId, id)
                .eq(UserOrder::getState, state)
                .eq(UserOrder::getDeleteStatus, 0)
                .orderByDesc(UserOrder::getAddTime);
        return userOrderService.list(wrapper);
    }
    @PostMapping ("/orders/count")
    @ApiOperation("统计订单数量")
    public Result countOrders(@RequestBody Map<String, Object> result){
        String id = (String) result.get("id");
        log.info("统计订单数量:{}", id);
        LambdaQueryWrapper<UserOrder> wrapper = new LambdaQueryWrapper<UserOrder>()
                .eq(UserOrder::getUserId, id)
                .eq(UserOrder::getDeleteStatus, 0)
                .orderByDesc(UserOrder::getAddTime);
        log.info("统计订单数量:{}", OrderStates.TOBEPAY.getName());
        LambdaQueryWrapper<UserOrder> wrapper1 = new LambdaQueryWrapper<UserOrder>()
                .eq(UserOrder::getUserId, id)
                .eq(UserOrder::getState, OrderStates.TOBEPAY.getName())
                .eq(UserOrder::getDeleteStatus, 0)
                .orderByDesc(UserOrder::getAddTime);
        LambdaQueryWrapper<UserOrder> wrapper2 = new LambdaQueryWrapper<UserOrder>()
                .eq(UserOrder::getUserId, id)
                .eq(UserOrder::getState, OrderStates.PAYED.getName())
                .eq(UserOrder::getDeleteStatus, 0)
                .orderByDesc(UserOrder::getAddTime);
        LambdaQueryWrapper<UserOrder> wrapper3 = new LambdaQueryWrapper<UserOrder>()
                .eq(UserOrder::getUserId, id)
                .eq(UserOrder::getState, OrderStates.DOWN.getName())
                .eq(UserOrder::getDeleteStatus, 0)
                .orderByDesc(UserOrder::getAddTime);
        OderDTO oderDTO = new OderDTO();
        oderDTO.setAll(userOrderService.count(wrapper));
        oderDTO.setPendingPayment(userOrderService.count(wrapper1));
        oderDTO.setPendingShipment(userOrderService.count(wrapper2));
        oderDTO.setCompleted(userOrderService.count(wrapper3));
        log.info("统计订单数量:{}", oderDTO);
        return Result.ok(oderDTO);
    }

    // 保存订单
    @PostMapping("/insert")
    @ApiOperation("保存订单")
    public Result insert(@RequestBody UserInfoDTO userInfoDTO){
        String orderId = userService.saveUserInfo(userInfoDTO);
        return Result.ok(orderId);
    }

    // 根据订单id查合同
    @GetMapping("/getOrderById/{id}")
    @ApiOperation("根据订单Id查询订单详情")
    public Result<UserInfoDTO> getOrderById(@PathVariable String id){
        UserInfoDTO userInfoDTO = userOrderService.getUserInfo(id);
        return Result.ok(userInfoDTO);
    }

    // 用户确认合同，订单状态改为待签署
    @PostMapping("/updateToBeSign")
    @ApiOperation("游客根据订单id修改订单状态")
    public Result updateToBeSign(@RequestParam @ApiParam("订单id") String orderId
            , @RequestParam  @ApiParam("订单状态") String state){
        UserOrder order = userOrderService.getById(orderId);
        order.setState(state);
        order.setModifyTime(DateUtils.getNowTime());
        userOrderService.updateById(order);
        return Result.ok();
    }

    @PostMapping("/bindUserAndAgent")
    @ApiOperation("游客与业务员绑定")
    public Result bindUserAndAgent(@RequestParam @ApiParam("用户id") String userId
            , @RequestParam  @ApiParam("业务员id") String agentId) {
        User user = new User();
        user.setId(userId);
        user.setAgentId(agentId);
        user.setState(1);  // 游客状态不变
        user.setModifyTime(DateUtils.getNowTime());
        userService.updateById(user);
        return Result.ok();
    }

    @GetMapping("/isBindWithAgent/{userId}")
    @ApiOperation("游客与业务员绑定校验")
    @ApiImplicitParam(name = "userId", value = "游客id")
    public Result userIsBindWithAgent(@PathVariable String userId) {
        // 根据用户openId查询agent_id字段的值
        String agentId = userService.getById(userId).getAgentId();
        if (agentId == null || agentId.isEmpty()) {
            return Result.ok();
        }
        return Result.ok(agentId);
    }
}
